from fastapi import APIRouter, Depends, UploadFile, File, BackgroundTasks, Query
from fastapi.responses import StreamingResponse
from app.core.deps import CurrentUser
from app.services.file_service import FileService
from app.schemas.file_schemas import FileResponse
from app.schemas.response import Response
from app.core.constants import MAX_FILE_SIZE, ALLOWED_FILE_TYPES
from app.core.i18n import t


router = APIRouter(prefix="/file", tags=["文件操作"])


@router.post("/upload", summary="上传文件", response_model=Response[FileResponse])
async def upload_file(
    file: UploadFile = File(...),
    background_tasks: BackgroundTasks = BackgroundTasks(),
    current_user: CurrentUser,
) -> Response[FileResponse]:
    """
    上传文件接口

    Args:
        file: 要上传的文件
        background_tasks: 后台任务
        current_user: 当前用户

    Returns:
        Response[FileResponse]: 文件上传响应

    Raises:
        APIException: 当文件类型不支持或文件大小超过限制时
    """
    # 验证文件类型
    if file.content_type not in ALLOWED_FILE_TYPES:
        return Response.error(t("error.file.invalid_type"))

    # 验证文件大小
    file.file.seek(0, 2)  # 移动到文件末尾
    size = file.file.tell()  # 获取文件大小
    file.file.seek(0)  # 重置文件指针
    if size > MAX_FILE_SIZE:
        return Response.error(t("error.file.size_exceeded"))

    service = FileService()
    return await service.upload_file(file, current_user.id, background_tasks)


@router.get("/url", summary="获取文件访问URL")
async def get_file_url(
    file_id: int = Query(..., description="文件ID", gt=0),
    current_user: CurrentUser,
) -> Response[str]:
    """
    获取文件访问URL接口

    Args:
        file_id: 文件ID
        current_user: 当前用户

    Returns:
        Response[str]: 文件访问URL
    """
    service = FileService()
    return await service.get_file_url(file_id)


@router.get("/download", summary="下载文件")
async def download_file(
    file_id: int = Query(..., description="文件ID", gt=0),
    current_user: CurrentUser,
) -> StreamingResponse:
    """
    下载文件接口

    Args:
        file_id: 文件ID
        current_user: 当前用户

    Returns:
        StreamingResponse: 文件流响应
    """
    service = FileService()
    file = await service.get_file_for_download(file_id)

    return StreamingResponse(
        file.file,
        media_type=file.content_type,
        headers={"Content-Disposition": f'attachment; filename="{file.filename}"'},
    )
